from fastapi import APIRouter, Depends
from app.api.deps import get_current_user, SessionDep, CurrentUser
from app.schemas.waveup.trading_pair import (
    WPTradingPairListQueryReq, 
    ProductSwapReq,
    WPTradingPairOut,
    PreProductSwapResp,
    PreProductSwapReq
)
from app.services.wp_service import query_wp_product_pair, wp_product_swap
from fastapi.exceptions import HTTPException
from app.crud.uc.partner_token import get_partner_token
from app.core.constants import ThirdPartner
from app.core.logger import logger
from app.services.nft_service import get_archive_ids
from app.crud.waveup.trading_pair import (
    get_trading_pair_list, 
    get_by_product_pair_id
)
from app.schemas.waveup.swap_record import SwapRecordCreate, SwapRecordUpdate
from app.crud.waveup.wp_user import get_wp_user_by_uid
from app.crud.waveup.swap_record import create_swap_record, update_swap_record, get_record_order_no
import ast
from app.schemas.waveup.swap_stat import SwapStatCreate, SwapStatUpdate
from app.core.utils import yuan_str_to_cents
from app.crud.waveup.swap_stat import get_swap_stat, create_swap_stat, update_swap_stat
from app.core.utils import gen_order_no
from app.services.redis_service import redis_set, redis_get
from datetime import datetime, timedelta
from app.core.constants import SwapRecordStatus

router = APIRouter(tags=["trading-pair"], prefix="/trading-pair")

@router.post("/list", dependencies=[Depends(get_current_user)])
async def get_trading_pairs(
    session: SessionDep,
    query: WPTradingPairListQueryReq,
):
    """查询WaveUp交易对列表"""
    # tradeStatus: 0待投票, 1投票中, 2 待开放, 3投票失败, 4开放中, 5：已停牌
    if not query.tradeStatusList:
        query.tradeStatusList = [4]
    # response = await query_wp_product_pair(
    #     pageNo=query.pageNo,
    #     pageSize=query.pageSize,
    #     tradeStatusList=query.tradeStatusList
    # )
    # if response["rc"] != 0:
    #     raise HTTPException(status_code=400, detail=response["msg"])
    # 为每个交易对添加XM藏品ID
    # for item in response["data"]["records"]:
    #     item["archiveIdA"] = await get_archive_id(session, item["productIdA"])
    #     item["archiveIdB"] = await get_archive_id(session, item["productIdB"])

    # 返回数据
    # return response["data"]

    # 测试数据(本地查询)
    response = await get_trading_pair_list(session, query)

    records = []
    for item in response["records"]:
        item = WPTradingPairOut.model_validate(item.model_dump())
        archiveA = await get_archive_ids(session, item.productIdA)
        item.archiveIdA = archiveA["archiveId"]
        item.platformIdA = archiveA["platformId"]
        archiveB = await get_archive_ids(session, item.productIdB)
        item.archiveIdB = archiveB["archiveId"]
        item.platformIdB = archiveB["platformId"]
        records.append(item)
    response["records"] = records

    return response

@router.post("/prev-swap", response_model=PreProductSwapResp)
async def prev_swap_product(
    req: PreProductSwapReq,
    current_user: CurrentUser,
):
    logger.info(f"prev_swap_product productPairId: {req.productPairId}")
    # 生成订单号
    swapOrderNo = gen_order_no(current_user.uid, "swap")
    redis_key = f"swap_order_no:{current_user.uid}"
    # 缓存到Redis
    await redis_set(
        key=redis_key,
        value=swapOrderNo,
        expire_seconds=60*10, # 10分钟过期
    )
    return {
        "orderNo": swapOrderNo,
        "expireAt": datetime.now() + timedelta(minutes=10),
    }

@router.post("/swap")
async def product_swap(
    session: SessionDep,
    req: ProductSwapReq,
    current_user: CurrentUser,
):
    # 从Redis获取订单号
    redis_key = f"swap_order_no:{current_user.uid}"
    swapOrderNo = await redis_get(redis_key)
    if not swapOrderNo:
        raise HTTPException(status_code=400, detail="订单号不存在或已过期")
    if req.orderNo != swapOrderNo:
        raise HTTPException(status_code=400, detail="订单号不匹配")
    # 查询订单是否已存储
    swap_record = await get_record_order_no(session=session, order_no=swapOrderNo)
    if swap_record:
        raise HTTPException(status_code=400, detail="重复下单")
    
    # 本地保存兑换订单
    trading_pair = await get_by_product_pair_id(session=session, product_pair_id=req.productPairId)
    if not trading_pair:
        # 记录日志，不抛出异常，兑换在waveup已完成
        logger.error(f"WaveUp产品兑换失败: 交易对不存在")
    wp_user = await get_wp_user_by_uid(session=session, uid=current_user.uid)
    if not wp_user:
        raise HTTPException(status_code=400, detail="WaveUp用户不存在")

    swap_record = SwapRecordCreate(
        uid=current_user.uid,
        swapOrderNo=swapOrderNo,
        productPairId=req.productPairId,
        fromProductId=req.fromProductId,
        fromAmount=req.fromAmount,
        toProductId=trading_pair.productIdB if trading_pair.productIdA == req.fromProductId else trading_pair.productIdA,
        toAmount=req.toAmount,
        slippage=req.slippage,
        profitAmount=req.profitAmount,
    )
    new_swap_record = await create_swap_record(session=session, swap_record_in=swap_record)

    """WaveUp藏品兑换"""
    # partner_token = await get_partner_token(
    #     session=session,
    #     uid=current_user.uid,
    #     partner=ThirdPartner.WaveUp,
    # )
    # if not partner_token:
    #     raise HTTPException(status_code=400, detail="Partner token not found")
    
    # waveup_req = WPProductSwapReq(
    #     accessToken=partner_token.accessToken,
    #     swapOrderNo=swapOrderNo,
    #     **req.model_dump()
    # )
    # response = await wp_product_swap(waveup_req, current_user.uid)
    # logger.info(f"WaveUp产品兑换响应: {response}")
    # if response["rc"] != 0:
    #     logger.error(f"WaveUp产品兑换失败: {response}")
    #     raise HTTPException(status_code=400, detail="藏品兑换失败")

    res_str = "{'data': {'id': '1990665251391614978', 'amountA': '10', 'amountB': '0.59586', 'exchangeType': 0, 'dealValue': '528', 'fee': '0.1'}, 'rc': 0, 'success': True}"
    response = ast.literal_eval(res_str)

    # 更新本地兑换记录
    swap_record = SwapRecordUpdate(
        id=new_swap_record.id,
        fromAmount=float(response["data"]["amountA"]),
        toAmount=float(response["data"]["amountB"]),
        wpSwapId=response["data"]["id"],
        exchangeType=int(response["data"]["exchangeType"]),
        dealValue=float(response["data"]["dealValue"]),
        fee=float(response["data"]["fee"]),
        status=SwapRecordStatus.Completed,
    )
    await update_swap_record(session=session, swap_record_in=swap_record)

    # 查询统计信息
    swap_stat = await get_swap_stat(
        session=session,
        uid=current_user.uid,
        product_pair_id=req.productPairId,
    )
    if not swap_stat:
        # 记录日志，不抛出异常，兑换在waveup已完成
        logger.info(f"WaveUp产品兑换成功: 兑换统计不存在，创建新的统计记录")
        swap_stat = SwapStatCreate(
            uid=current_user.uid,
            productPairId=req.productPairId,
            swapCount=1,
            swapAmount=yuan_str_to_cents(req.profitAmount),
        )
        await create_swap_stat(session=session, swap_stat_in=swap_stat)
    else:
        # 更新统计信息
        swap_stat = SwapStatUpdate(
            id=swap_stat.id,
            swapCount=1,
            swapAmount=yuan_str_to_cents(req.profitAmount),
        )
        await update_swap_stat(session=session, swap_stat_in=swap_stat)
    
    return response["data"]